package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.common.MessageConst;
import com.itheima.common.RedisConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.sercive.SetmealService;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetMealController {
    @Reference
    SetmealService setmealService;



    @RequestMapping("/getToken")
    public Result getToken() {
        String accessKey = "AnsdGV-d6vuDEMJ5-Wlodzcz7hKr3eKEWWs6vuSG";
        String secretKey = "16y6T5OT882AzEEFMjS8_9fJBPQqOdf_ZKFyOhEF";
        String bucket = "wodeqiniuyunkongjian";
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(bucket);
        return new Result(true, MessageConst.GET_QINIU_TOKEN_SUCCESS, uploadToken);
    }
    @RequestMapping("/add")
    public Result add(@RequestBody Map<String,Object> map) {
        JSONObject jsonObject = (JSONObject) map.get("setmeal");
        Setmeal setmeal = jsonObject.toJavaObject(Setmeal.class);
        JSONArray jsonArray = (JSONArray) map.get("checkgroupIds");
        Integer[] checkgroupIds = jsonArray.toArray(new Integer[]{});
        setmealService.add(setmeal,checkgroupIds);
        return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        log.debug("SetmealControlller:findPage:" + queryPageBean);
        PageResult pageResult = setmealService.findPage(queryPageBean);
        log.debug("套餐查询成功！！");
        return pageResult;
    }

    @Autowired
    JedisPool jedisPool;
    @RequestMapping("/saveImgName")
    public Result addImgName(String imgName) {
        log.debug("SetmealControlller:addImgName:" + imgName);
        if (imgName!=null) {
            Jedis jedis = jedisPool.getResource();
            jedis.sadd(RedisConst.SETMEAL_PIC_RESOURCES, imgName);
            log.debug("图片名称添加到redis成功！！");
        }
        return new Result(true,MessageConst.ADD_IMGNAME_REDIS);
    }
}
